package com.github.m6d21.sso.business.configuration;

import com.github.m6d21.sso.support.interceptor.SsoLoginInterceptor;
import com.github.m6d21.sso.support.model.WebInterceptorWrapper;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 *<p>
 *spring mvc拦截器配置
 *</p>
 *
 * @author liuyang
 * @date 2019/1/2 Wed 10:45:00
 * @since 1.0.0
 */
@Configuration
public class SsoInterceptorConfiguration implements WebMvcConfigurer {

    private static final Logger LOG = LoggerFactory.getLogger(SsoInterceptorConfiguration.class);

    @Value("${sso.token.expire}")
    private Integer tokenExpire = 3600;
    @Value("${sso.login.url}")
    private String loginUrl = "/login";
    @Value("${sso.login.restful.api}")
    private String loginRestfulApi = "/web/login";
    @Value("${sso.intercept.enabled}")
    private Boolean enabled = true;

    @Bean
    SsoLoginInterceptor ssoLoginInterceptor() {
        SsoLoginInterceptor ssoLoginInterceptor = new SsoLoginInterceptor();
        ssoLoginInterceptor.setTokenExpire(tokenExpire);
        ssoLoginInterceptor.setLoginUrl(loginUrl);
        ssoLoginInterceptor.setLoginRestfulApi(loginRestfulApi);
        ssoLoginInterceptor.setEnabled(enabled);
        return ssoLoginInterceptor;
    }

    @Bean(name = "ssoLoginInterceptorWrapper")
    WebInterceptorWrapper ssoLoginInterceptorWrapper() {
        WebInterceptorWrapper webInterceptorWrapper = new WebInterceptorWrapper();
        webInterceptorWrapper.setIncludePattern("/**");
        webInterceptorWrapper.setExcludePatternList(Lists.newArrayList(
            loginUrl, "/web/register",
            "/login.htm", "/login.html", "/web/user/exist/username"
        ));
        webInterceptorWrapper.setInterceptor(ssoLoginInterceptor());
        return webInterceptorWrapper;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        WebInterceptorWrapper interceptorWrapper = ssoLoginInterceptorWrapper();
        registry.addInterceptor(interceptorWrapper.getInterceptor())
            .addPathPatterns(interceptorWrapper.getIncludePattern())
            .excludePathPatterns(interceptorWrapper.getExcludePatternList());
    }
}
